<script lang="ts" setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'

import { curTopMessage, topMessage } from './data'
import { safeArea } from '@/libs/config'

const top = safeArea.top2 + 50 + 'rpx'
let pageIdx = -1

/** 是否开启组件 */
const enable = ref(false)
/** 是否显示UI */
const showUI = ref(false)

watch(curTopMessage, (val) => {
  if (val) {
    if (pageIdx !== getCurrentPages().length - 1) return

    enable.value = true

    // bug 渲染帧有概率冲突
    setTimeout(() => showUI.value = true, 50)
  } else {
    showUI.value = false
    enable.value = false
  }
})

onMounted(() => {
  pageIdx = topMessage.ready++
  topMessage.set()
})

onBeforeUnmount(() => {
  topMessage.ready--
  curTopMessage.value = undefined
})
</script>

<template>
  <!-- 简单过度组件 -->
  <div
    v-if="enable"
    class="top-msg"
    :class="{ show: showUI, [curTopMessage?.type || '']: true }"
    :style="{ top }"
  >{{ curTopMessage?.text }}</div>
</template>

<style lang="less" scoped>
.top-msg {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -100rpx)scale(0);
  max-width: 80%;
  padding: 10rpx 20rpx;
  background-color: #111;

  opacity: 0;
  pointer-events: none;

  color: #fff;
  font-size: 32rpx;
  line-height: 40rpx;
  text-align: center;
  white-space: pre-wrap;
  word-break: break-all;

  border: 2rpx solid #fff;
  box-shadow: 0 0 20rpx #fff;
  border-radius: 15rpx;

  transition: transform .3s, opacity.3s;

  z-index: 100;

  &.show {
    opacity: 1;
    transform: translate(-50%, 100rpx)scale(1);
    pointer-events: all;
  }

  &.error {
    color: #ff7070;
    border-color: #ff7070;
    box-shadow: 0 0 20rpx #ff7070;
  }

  &.success {
    color: #7aff7a;
    border-color: #7aff7a;
    box-shadow: 0 0 20rpx #7aff7a;
  }

  &.warn {
    color: #ffa743;
    border-color: #ffa743;
    box-shadow: 0 0 20rpx #ffa743;
  }

  &.system {
    color: #43baff;
    border-color: #43baff;
    box-shadow: 0 0 20rpx #43baff;
  }
}
</style>